/* eslint-disable sonarjs/no-duplicate-string */
import { ArrowDown, ArrowRight, ArrowUp } from '@nutui/icons-react';
import { Image, Toast } from '@nutui/nutui-react';
import { cloneDeep, uniqueId } from 'lodash-es';
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useNavigate } from 'react-router-dom';

import { apiOrderQueryCardsByGet } from '@/application/apis/order';
import { classNames, classNames as classnames } from '@/application/utils';
import { copy } from '@/application/utils/copy';
import { AbcCard, AbcCardsInfoDto } from '@/types/apiType';

export const RewardCard: React.FC<
  any & {
    handleLook: (params: any) => void;
    handleReceive: (params: any) => void;
  }
> = (props) => {
  const { className, item, handleLook, handleReceive } = props;

  const [coupon, setCoupon] = useState<any[]>([]);
  const [expand, setExpand] = useState(false);

  const interval = useRef<NodeJS.Timeout>();
  useEffect(() => {
    if (item.goodsType === 7 && item.status === 2) {
      refreshCouponInfo();
      interval.current = setInterval(refreshCouponInfo, 1000);
    }
    return () => {
      interval.current && clearInterval(interval.current);
    };
  }, [item]);

  const refreshCouponInfo = useCallback(() => {
    apiOrderQueryCardsByGet({ winId: item.id }, { hideLoading: true }).then(
      (res: AbcCardsInfoDto | undefined) => {
        const n: any[] = res?.Card || [];

        setCoupon(cloneDeep(n));

        if (n.length > 0) {
          clearInterval(interval.current);
        }
      }
    );
  }, [item]);

  const handleCopy = (e: AbcCard) => {
    // 获取要复制的文本
    const code = `${e.CardPwd}`;
    copy(code);

    Toast.show({
      title: '复制成功',
      lockScroll: true
    });
  };

  const isXingbake = useMemo(() => {
    return coupon.length > 0 && (coupon[0].CardPwd || '').startsWith('https://');
  }, [coupon]);
  return (
    <div
      className={classnames(
        'after:border-[rgba(198, 198, 198, .3)]  relative flex h-fit items-center px-3.75 py-3.25 after:absolute after:bottom-0 after:left-3.75 after:right-0 after:border-b',
        className
      )}
      key={item.id}
    >
      <Image src={item.picture} className="mr-2.5 h-17.5 w-17.5 flex-shrink-0 self-start" />
      <div className="flex flex-1 flex-col justify-between">
        <div className="min-h-13.5">
          <div className="line-clamp-2 font-medium">{item.goodsName}</div>
          <div className="mt-2.5 text-xs text-[#999]">{`${item.createTime}获得`}</div>
          <div className="flex justify-between">
            <div
              className={classNames('invisible mt-2.5 flex items-center text-xs text-[#FE4F05]', {
                visible: item.status === 2 && item.goodsType !== 7
              })}
              onClick={() => handleLook(item)}
            >
              查看领取信息
              <ArrowRight className="!h-3 !w-3" />
            </div>

            <div className="ml-2.5  w-18.75 self-end text-right">
              {item.status === 1 ? (
                <div
                  className="flex flex-shrink-0 items-center justify-center rounded-full bg-[#FE4F05] py-2 text-sm font-medium text-white"
                  onClick={() => handleReceive(item)}
                >
                  领取奖励
                </div>
              ) : isXingbake ? (
                <div
                  className="flex flex-shrink-0 items-center justify-center rounded-full bg-[#FE4F05] py-2 text-sm font-medium text-white"
                  onClick={() => (window.location.href = coupon[0].CardPwd)}
                >
                  兑换码
                </div>
              ) : (
                <div className="text-sm text-[#999]">已领取</div>
              )}
            </div>
          </div>
        </div>

        <div>
          <div className="mt-[5px]">
            {coupon && coupon.length > 0 && !isXingbake && (
              <div className="mb-[15px] grid gap-[5px] rounded-sm">
                {coupon.map((e, index) => (
                  <div
                    key={uniqueId()}
                    className={classnames(' grid gap-1 bg-[#f6f6f6] p-2.5', {
                      hidden: !expand && index > 4
                    })}
                  >
                    <div className="text-xs text-[#999999]">卡号:{e?.CardNo || ''}</div>
                    <div className="flex justify-between text-xs text-[#333333]">
                      卡密:{e?.CardPwd || ''}
                      <div className="text-[#FF4800]" onClick={() => handleCopy(e)}>
                        复制
                      </div>
                    </div>
                  </div>
                ))}
                {coupon.length >= 5 && (
                  <div
                    onClick={() => setExpand((prev) => !prev)}
                    className={classnames(
                      'mt-2.5 flex items-center justify-center text-center text-xs'
                    )}
                  >
                    {expand ? '收起' : '展开全部'}
                    {expand ? <ArrowUp className="ml-1" /> : <ArrowDown className="ml-1" />}
                  </div>
                )}
              </div>
            )}
          </div>
        </div>
      </div>
    </div>
  );
};
